package com.tyl.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tyl.ResultEntity;
import com.tyl.entity.Menu;
import com.tyl.service.IMenuService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author 汤云龙
 * @since 2022-03-17
 */
@RestController
@RequestMapping("/resource")
public class MenuController {
    @Resource
    private IMenuService menuService;
    @GetMapping("/showUserMenu")
    public ResultEntity showUserMenu(){
        // toDo这是user的标记
        int userId=2;
        List<Menu> menus = menuService.selectByMenu(userId);
        return ResultEntity.ok(menus);
    }
    @GetMapping("/showAllResourceTree")
    public ResultEntity showAllResourceTree(){
        //查询所有的菜单
        List<Menu> menuList = menuService.list();
        //过滤所有的一级菜单
        List<Menu> menuTree = menuList.stream().filter((m) -> {
            return m.getType().equals(0);
        })
                .peek((m)->{m.setChild(child(m.getMenuId(),menuList));}).collect(Collectors.toList());
        return ResultEntity.ok(menuTree);
    }
    private List<Menu> child(Long menuId,List<Menu> menuList){
        return  menuList.stream().filter((m)->{return m.getParentId()==menuId;})
                .peek((m)->{m.setChild(child(m.getMenuId(),menuList));}).collect(Collectors.toList());

    }
    @GetMapping("/selectAll")
    public ResultEntity selectAllMenu(){
        //查询所以的权限列表
        List<Menu> list = menuService.list();
        return ResultEntity.ok(list);
    }
    @GetMapping("/selectOne/{resourceId}")
    public ResultEntity selectByMenu(@PathVariable("resourceId") Integer resourceId ){
        Menu menu = menuService.getById(resourceId);
        return ResultEntity.ok(menu);

    }
    @PutMapping("/update")
    public ResultEntity updateMenu(@RequestBody Menu menu){
        //修改权限
        QueryWrapper<Menu> menuQueryWrapper = new QueryWrapper<>();
        menuQueryWrapper.eq("menu_id",menu.getMenuId());
        menuService.update(menu,menuQueryWrapper);
        return ResultEntity.ok();
    }
    @GetMapping("/selectChildrenByPid/{resourceId}")
    public ResultEntity selectChildrenByPid(@PathVariable("resourceId") Integer resourceId){
        List<Menu> menuList = menuService.selectByMenuId(resourceId);
        return ResultEntity.ok(menuList);
    }



}

